import React from 'react'
import { Table,Icon,Modal,Popconfirm,Form,Input,Row,Col,DatePicker,Button,Message,Select} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import api from '../../../api/communityHouseCost';

const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import {jsonToTree} from '../../../utils/tools'

import '../../../style/antd-theme.less';

export default class TablePage extends React.Component {
  state = {
    data: [],
    pagination: {
      pageSize:20,
      pageNum:1,
    },
    loading: false, 
  };
  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
   
    this.fetch({...pagination});
  }
  fetch = (params) => {
    this.setState({ loading: true });
    api.get('/communityCost/getAll', { params}).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () =>{
    this.fetch({ ...this.state.pagination });

  }

  
  delete = (id,event) => {
    api.delete('/communityCost/delete', {id:id}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('删除成功！');
      this.fetch();
     }else{
      Message.error(result.message);
     }
    });
  }
  updateHasGive = (id,event) => {
    api.put('/communityCost/updateHasGive', {id:id,hasGive:1}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('操作成功！');
      this.fetch();
     }else{
      Message.error(result.message);
     }
     this.setState({
       sumitLoad: false
     });
    });
  }
  createCost = () => {
    var values=[];
    let user =this.props.profile.user;
    values.office_id =user.officeId;
    api.post('/communityCost/add', {...values}).then((data) => {
    const result= data.data;
     if(result.code == 0){
      Message.success('生成成功！');
      this.fetch();
     }else{
      Message.error(result.message);
     }
     this.setState({
        sumitLoad: false
      });
    });
  }

  render() {
    let columns = [{
      title: '房间名称',
      dataIndex: 'houseName',
      render:(text, record, index) =>  (
        <span>{record.parentName}</span>
      ),
    },{
      title: '业主信息',
      dataIndex: 'userName',
      width: '18%',
      render:(text, record, index) =>  (
        <span>{record.userName}（{record.userMobile}）</span>
      ),
    },{
      title: '所属日期',
      dataIndex: 'yearMouth',
      width: '10%',
    }, {
      title: '缴纳费用',
      dataIndex: 'cost',
      width: '10%',
    }, {
      title: '费用类型',
      dataIndex: 'type',
      width: '10%',
      render:(text, record, index) =>  {
        switch(record.type){
          case '0':
            return '其他费用';
          case '1':
            return '物管费';
          default:
            return '未知';
        }
      },
    }, {
      title: '是否缴纳',
      dataIndex: 'hasGive',
      width: '10%',
      render:(text, record, index) =>  {
        switch(record.hasGive){
          case '2':
            return '未交';
          case '1':
            return '已交';
          default:
            return '未知';
        }
      },
    }, {
      title: '操作',
      key: 'action',
      width: '13%',
      render: (text, record) => (
        <span>
          <Popconfirm title="您是否要删除该记录?" onConfirm={this.delete.bind(this,record.id)} okText="是" cancelText="否">
            <a href="javascript:void(0)">删除</a>
          </Popconfirm>
          { record.hasGive == 2 ?
          <span>
          <span className="ant-divider" />
          
          <Popconfirm title="您是否确认将此业主物业费标记为已交?" onConfirm={this.updateHasGive.bind(this,record.id)} okText="是" cancelText="否">
            <a href="javascript:void(0)" >标记为已交</a>
          </Popconfirm>
          </span>
          : ''}
        </span>
      ),
    }];
    return (
      <div>
        <SearchCostForm searchCostState={this.state} goSearch={this.handleTableChange} createCost={this.createCost}/>
        <PanelBox>
          <Table columns={columns}  dataSource={this.state.data}  pagination={this.state.pagination}
            loading={this.state.loading}  onChange={this.handleTableChange}  rowKey={'id'}
            expandedRowRender={record => <p style={{ margin: 0 }}>更新时间 : {record.updateDate}</p>}
          />
        </PanelBox>
      </div>
    );
  }
}

    class SearchsForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        let params=this.props.form.getFieldsValue();
        
        let _this=this.props;
        params.pageSize=_this.searchCostState.pagination.pageSize;
        params.pageNum =1;
        params.current =1;
        
        if(params.date.length > 0){
          params.startYearMouth=moment(params.date[0]).format("YYYY-MM-DD");
          params.endYearMouth=moment(params.date[1]).format("YYYY-MM-DD");
        }
        delete params.date;
        if(params.hasGive == -1){
         delete params.hasGive;
        }
        if(params.type == -1){
         delete params.type;
        }
        _this.goSearch(params);
     
      }

      srearchStyle = {
        labelCol: { span: 8},
        wrapperCol: { span: 14 },
      };
     
      render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = this.srearchStyle;

        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          <FormItem {...formItemLayout} label="房间名称" style={{marginRight:0,marginBottom:'10px'}}>
            {getFieldDecorator('houseName')(
              <Input type="text" placeholder="请输入房间名称"/>
            )}
          </FormItem>
          
          <FormItem {...formItemLayout} label="业主姓名">
            {getFieldDecorator('userName' )(
              <Input type="text" placeholder="请输入业主姓名"/>
            )}
          </FormItem>
          
          <FormItem {...formItemLayout} label="业主电话">
            {getFieldDecorator('userMobile' )(
              <Input type="text" placeholder="请输入业主电话"/>
            )}
          </FormItem>
          
          <FormItem {...formItemLayout} label="所属日期" style={{marginLeft:'-50px'}}>
            {getFieldDecorator('date' ,{ initialValue:[] } )(
              <RangePicker format="YYYY/MM/DD" />
            )}
          </FormItem>
          <FormItem  {...formItemLayout}   label="是否缴纳" style={{marginLeft:'4px'}}>
            {getFieldDecorator('hasGive',{ initialValue:'-1' } )(
              <Select style={{ width: 139 }}>
                <Option value="1">已交</Option>
                <Option value="0">未交</Option>
                <Option value="-1">全部</Option>
              </Select>
            )}
          </FormItem>
          
          <FormItem  {...formItemLayout}  label="费用类型">
            {getFieldDecorator('type',{ initialValue:'-1' })(
              <Select style={{ width: 139 }}>
                <Option value="1">物管费用</Option>
                <Option value="0">其他费用</Option>
                <Option value="-1">全部</Option>
              </Select>
            )}
          </FormItem>
          <FormItem>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem> 
          <FormItem>
            <Popconfirm title="您是否确认生成当月物管费?" onConfirm={this.props.createCost} okText="是" cancelText="否">
              <Button type="primary" >生成当月物管费</Button>
            </Popconfirm>
          </FormItem>
        </Form>
      }
    }
    const SearchCostForm = Form.create({})(SearchsForm);